const app = getApp();

Page({
  data: {
    list: [],
    page: 1,
    limit: 20,
    total: 0,
    hasMore: true
  },

  onLoad() {
    this.loadList();
  },

  onPullDownRefresh() {
    this.setData({
      page: 1,
      list: [],
      hasMore: true
    });
    this.loadList(() => {
      wx.stopPullDownRefresh();
    });
  },

  loadList(callback) {
    wx.showLoading({ title: '加载中...' });
    
    wx.request({
      url: app.globalData.baseUrl + '/getQualityRecords',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + app.globalData.token
      },
      data: {
        page: this.data.page,
        limit: this.data.limit
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.data.code === 1) {
          const newList = res.data.data.list || [];
          
          // 格式化数据
          newList.forEach(item => {
            item.check_time_text = this.formatTime(item.check_time);
            item.createtime_text = this.formatTime(item.createtime);
          });
          
          this.setData({
            list: this.data.page === 1 ? newList : [...this.data.list, ...newList],
            total: res.data.data.total,
            hasMore: newList.length >= this.data.limit
          });
        } else {
          wx.showToast({
            title: res.data.msg || '加载失败',
            icon: 'none'
          });
        }
        
        if (callback) callback();
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
        if (callback) callback();
      }
    });
  },

  loadMore() {
    if (!this.data.hasMore) return;
    
    this.setData({
      page: this.data.page + 1
    });
    this.loadList();
  },

  goToDetail(e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/quality-record-detail/quality-record-detail?id=${id}`
    });
  },

  formatTime(timestamp) {
    const date = new Date(timestamp * 1000);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hour = String(date.getHours()).padStart(2, '0');
    const minute = String(date.getMinutes()).padStart(2, '0');
    return `${year}-${month}-${day} ${hour}:${minute}`;
  }
});
